package com.nttdata.ta.todo.controller;

import com.nttdata.ta.common.dto.ResponseResult;
import com.nttdata.ta.common.dto.TodoDTO;
import com.nttdata.ta.todo.service.TodoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.function.Function;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/todos")
public class TodoRestController {
    
    private final TodoService todoService;
    
    @GetMapping
    public ResponseEntity<ResponseResult<List<TodoDTO>>> getAllTodos(@RequestHeader("Authorization") String authHeader) {
        return processRequest(authHeader, token -> {
            Long userId = todoService.getUserIdFromToken(token);
            return todoService.getAllTodosByUserId(userId);
        }, "获取待办事项列表");
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<ResponseResult<TodoDTO>> getTodoById(
            @PathVariable Long id,
            @RequestHeader("Authorization") String authHeader) {
        return processRequest(authHeader, token -> {
            TodoDTO todo = todoService.getTodoById(id);
            
            // 验证用户是否有权限访问此待办事项
            Long userId = todoService.getUserIdFromToken(token);
            if (!userId.equals(todo.getUserId())) {
                throw new SecurityException("没有访问权限");
            }
            
            return todo;
        }, "获取待办事项详情");
    }
    
    @PostMapping
    public ResponseEntity<ResponseResult<TodoDTO>> createTodo(
            @RequestBody TodoDTO todoDTO,
            @RequestHeader("Authorization") String authHeader) {
        return processRequest(authHeader, token -> {
            Long userId = todoService.getUserIdFromToken(token);
            todoDTO.setUserId(userId); // 设置用户ID
            
            TodoDTO createdTodo = todoService.createTodo(todoDTO);
            return createdTodo;
        }, "待办事项创建成功");
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<ResponseResult<TodoDTO>> updateTodo(
            @PathVariable Long id,
            @RequestBody TodoDTO todoDTO,
            @RequestHeader("Authorization") String authHeader) {
        return processRequest(authHeader, token -> {
            // 验证用户是否有权限修改此待办事项
            TodoDTO existingTodo = todoService.getTodoById(id);
            Long userId = todoService.getUserIdFromToken(token);
            
            if (!userId.equals(existingTodo.getUserId())) {
                throw new SecurityException("没有访问权限");
            }
            
            return todoService.updateTodo(id, todoDTO);
        }, "待办事项更新成功");
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<ResponseResult<Void>> deleteTodo(
            @PathVariable Long id,
            @RequestHeader("Authorization") String authHeader) {
        return processRequest(authHeader, token -> {
            // 验证用户是否有权限删除此待办事项
            TodoDTO existingTodo = todoService.getTodoById(id);
            Long userId = todoService.getUserIdFromToken(token);
            
            if (!userId.equals(existingTodo.getUserId())) {
                throw new SecurityException("没有访问权限");
            }
            
            todoService.deleteTodo(id);
            return null;
        }, "待办事项删除成功");
    }
    
    /**
     * 统一处理令牌验证和异常处理的工具方法
     * @param authHeader 认证头
     * @param processor 业务处理函数
     * @param successMessage 成功消息
     * @return ResponseEntity结果
     */
    private <T> ResponseEntity<ResponseResult<T>> processRequest(
            String authHeader, 
            Function<String, T> processor,
            String successMessage) {
        try {
            // 解析令牌
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ResponseEntity.status(401).body(ResponseResult.fail(401, "未提供令牌或格式错误"));
            }
            
            String token = authHeader.substring(7); // 去掉"Bearer "前缀
            
            // 验证令牌
            if (!todoService.validateToken(token)) {
                return ResponseEntity.status(401).body(ResponseResult.fail(401, "无效的令牌"));
            }
            
            // 执行业务逻辑
            T result = processor.apply(token);
            
            // 成功响应
            return ResponseEntity.ok(ResponseResult.success(successMessage, result));
        } catch (SecurityException e) {
            // 权限异常处理
            log.warn("权限错误: {}", e.getMessage());
            return ResponseEntity.status(403).body(ResponseResult.fail(403, e.getMessage()));
        } catch (Exception e) {
            // 其他异常处理
            log.error("处理请求失败", e);
            return ResponseEntity.badRequest().body(ResponseResult.fail(e.getMessage()));
        }
    }
} 